package consistentHash;

import java.util.Arrays;

/**
 * @author 03010570
 * @date 2020/07/07
 * describe:
 */
public class MyServiceNode  {

    public static void main(String[] args) {
        //initialize 4 service node
        PhysicalNode node1 = new PhysicalNode("IDC1","127.0.0.1",8080);
        PhysicalNode node2 = new PhysicalNode("IDC1","127.0.0.1",8081);
        PhysicalNode node3 = new PhysicalNode("IDC1","127.0.0.1",8082);
        PhysicalNode node4 = new PhysicalNode("IDC1","127.0.0.1",8084);

        //hash them to hash ring
        ConsistentHashRouter consistentHashRouter = new ConsistentHashRouter(Arrays.asList(node1, node2, node3, node4), 10);//10 virtual node

        //we have 5 requester ip, we are trying them to route to one service node
        String requestIP1 = "192.168.0.1";
        String requestIP2 = "192.168.0.2";
        String requestIP3 = "192.168.0.3";
        String requestIP4 = "192.168.0.4";
        String requestIP5 = "192.168.0.5";

        goRoute(consistentHashRouter,requestIP1,requestIP2,requestIP3,requestIP4,requestIP5);

        PhysicalNode node5 = new PhysicalNode("IDC2","127.0.0.1",8080);//put new service online
        System.out.println("-------------putting new node online " +node5.toString()+"------------");
        consistentHashRouter.addPhysicalNode(node5,10);

        goRoute(consistentHashRouter,requestIP1,requestIP2,requestIP3,requestIP4,requestIP5);

        consistentHashRouter.removePhysicalNode(node3);
        System.out.println("-------------remove node online " + node3.toString() + "------------");
        goRoute(consistentHashRouter,requestIP1,requestIP2,requestIP3,requestIP4,requestIP5);


    }

    private static void goRoute(ConsistentHashRouter consistentHashRouter ,String ... requestIps){
        for (String requestIp: requestIps) {
            System.out.println(requestIp + " is route to " + consistentHashRouter.getPhysicalNodeByKey(requestIp));
        }
    }
}
